<template>
  <div>
    <div style="margin: 10px;text-align: center;">
      <!-- <el-button
        class="filter-item"
        style="margin-right: 100px"
        type="primary"
        icon="el-icon-edit"
        size="small"
        @click="handleCreate"
      >
        添加实体
      </el-button> -->
      <el-input
        v-model="cdtSname"
        class="filter-item"
        style="width: 200px; margin-right: 10px"
        placeholder="店铺"
        size="small"
      />
      <!-- <el-input
        v-model="cdtAddress"
        class="filter-item"
        style="width: 200px; margin-right: 10px"
        placeholder="地址"
        size="small"
      />
      <el-input
        v-model="cdtMname"
        class="filter-item"
        style="width: 200px; margin-right: 10px"
        placeholder="中台社群"
        size="small"
      />
      <el-input
        v-model="cdtDeveloper"
        class="filter-item"
        style="width: 200px; margin-right: 10px"
        placeholder="开发人员"
        size="small"
      />
      <el-select
        class="filter-item"
        style="margin-right: 10px"
        size="small"
        v-model="cdnStatus"
        placeholder="机构状态"
      >
        <el-option :key="0" label="履约期" :value="0" />
        <el-option :key="1" label="试用期" :value="1" />
        <el-option :key="2" label="停滞期" :value="2" />
      </el-select> -->
      <el-button
        class="filter-item"
        style="margin-right: 10px"
        type="primary"
        icon="el-icon-search"
        size="small"
        @click="searchSalon"
      >
        查询
      </el-button>
      <el-button
        class="filter-item"
        style="margin-right: 10px"
        icon="el-icon-refresh"
        size="small"
        @click="resetSalon"
      >
        重置
      </el-button>
    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column
        prop="sname"
        label="店铺名称"
        align="center"
        show-overflow-tooltip
      />
      <el-table-column
        prop="code"
        label="店铺编号"
        align="center"
        width="130"
      />
      <el-table-column
        prop="address"
        label="店铺地址"
        align="center"
        show-overflow-tooltip
      />
      <el-table-column
        prop="tel"
        label="联系方式"
        align="center"
        width="110"
        show-overflow-tooltip
      />
      <el-table-column
        prop="accountNum"
        label="账号数"
        align="center"
        width="70"
      />
      <el-table-column
        label="账号管理"
        align="center"
        width="110"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{ row }">
          <el-button type="text" size="mini" @click="nav2Account(row)">
            查看账号
          </el-button>
        </template>
      </el-table-column>
      <el-table-column
        prop="consumerNum"
        label="顾客数"
        align="center"
        width="70"
      />
      <el-table-column
        label="顾客管理"
        align="center"
        width="110"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{ row }">
          <el-button type="text" size="mini" @click="nav2Consumer(row)">
            查看顾客
          </el-button>
        </template>
      </el-table-column>
      <el-table-column
        prop="remark"
        label="说明"
        align="center"
        width="200"
        show-overflow-tooltip
      />
      <el-table-column
        label="操作"
        align="center"
        width="210"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{ row, $index }">
          <el-button v-if="row.isFrozen===0" type="warning" size="mini" plain @click="frozeStore(row, 1)">
            停用
          </el-button>
          <el-button v-else type="success" size="mini" plain @click="frozeStore(row, 0)">
            启用
          </el-button>
          <el-button
            type="primary"
            size="mini"
            plain
            @click="handleUpdate(row)"
          >
            查看
          </el-button>
          <el-button
            type="danger"
            size="mini"
            plain
            @click="handleDelete(row.id, $index)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="fetchData" />

    <el-dialog :title="title" :visible.sync="dialogFormVisible" style="margin-top: -120px">
      <el-form
        ref="dataForm"
        :model="salonObj"
        label-width="110px"
        style="margin-right: 30px"
        :rules="rules"
      >
        <el-row :gutter="0">
          <el-col :span="24" :offset="0">
            <el-form-item label="店铺全称" prop="sname">
              <el-input v-model="salonObj.sname" />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="11" :offset="1">大B端：
            <el-select v-model="salonObj.bid" placeholder="请选择大B端" style="width: 80%;">
              <el-option
                v-for="item in listB"
                :key="item.id"
                :label="item.bname"
                :value="item.id"
              />
            </el-select>
          </el-col> -->
        </el-row>
        <el-form-item v-show="title == '查看'" label="店家编号">
          <el-input v-model="salonObj.code" :disabled="true" />
        </el-form-item>
        <el-form-item v-show="title == '查看'" label="店家地址">
          <el-input v-model="salonObj.address" />
        </el-form-item>
        <el-form-item v-show="title == '新增'" label="店家地址">
          <div style="display: grid">
            <el-cascader
              v-model="selectedOptions"
              :options="areaSelectData"
              style="width: 260px"
              :filterable="true"
              size="medium"
              @change="locationHandleChange"
            />
            <el-input
              v-model="addr2"
              autocomplete="off"
              style="width: 76%; margintop: 10px"
              placeholder="街道门牌号"
            />
          </div>
        </el-form-item>
        <!-- <el-form-item label="大B端">
          <el-input v-model="salonObj.bigbend" />
        </el-form-item> -->
        <el-form-item label="店铺业态">
          <el-checkbox-group v-model="checkList">
            <el-checkbox label="1">【生美】美睫美甲纹绣</el-checkbox>
            <el-checkbox label="2">【生美】面（头）部类</el-checkbox>
            <el-checkbox label="3">【生美】身体类</el-checkbox>
            <el-checkbox label="4">【生美】中医养生类</el-checkbox>
            <el-checkbox label="5">【生美】大健康类</el-checkbox>
            <el-checkbox label="6">【轻医美机构】</el-checkbox>
            <el-checkbox label="7">【综合医美机构】</el-checkbox>
            <el-checkbox label="8">【异业】服务女性的非美业</el-checkbox>
            <el-checkbox label="9">其他</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <!-- <el-form-item label="中台社群">
          <el-radio-group v-model="salonObj.mid">
            <el-radio v-for="(item, index) in lstComms" :key="index" :label="item.id" style="margin-right: 10px">{{ item.nickName }}</el-radio>
          </el-radio-group>
        </el-form-item> -->
        <!-- <el-form-item label="医美机构">
          <el-radio-group v-model="salonObj.oid">
            <el-radio-button v-for="(item, index) in lstYm" :key="index" :label="item.id" style="margin-right: 10px">{{ item.nickName }}</el-radio-button>
          </el-radio-group>
        </el-form-item> -->
        <el-row :gutter="0">
          <el-col :span="7" :offset="0">
            <el-form-item label="联系方式">
              <el-input v-model="salonObj.tel" />
            </el-form-item>
          </el-col>
          <el-col :span="10" :offset="0">
            <el-form-item label="店铺面积">
              <el-input-number
                v-model="salonObj.area"
                :min="1"
                controls-position="right"
              />
              · 平米
            </el-form-item>
          </el-col>
          <el-col :span="7" :offset="0">
            <el-form-item label="店铺人数">
              <el-input-number
                  v-model="salonObj.cnumber"
                  :min="1"
                  controls-position="right"
                />
              </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="0">
          <el-col :span="7" :offset="0">
            <el-form-item label="开发人员">
              <el-input v-model="salonObj.developer" />
            </el-form-item>
          </el-col>
          <el-col :span="7" :offset="0">
            <el-form-item label="专属客服">
              <el-input v-model="salonObj.server" />
            </el-form-item>
          </el-col>
          <el-col :span="10" :offset="0">
            <el-form-item
                style="margin-bottom: 10px"
                label-width="100px"
                label="机构状态"
            >
              <el-radio v-model="salonObj.status" :label="0">履约期</el-radio>
              <el-radio v-model="salonObj.status" :label="1">试用期</el-radio>
              <el-radio v-model="salonObj.status" :label="2">停滞期</el-radio>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注说明">
          <el-input v-model="salonObj.remark" />
        </el-form-item>
        <el-form-item label="历史客服">
          <el-input v-model="salonObj.history" :autosize="{ minRows: 1, maxRows: 4 }" type="textarea" disabled/>
        </el-form-item>
        <el-form-item label="合作条款">
          <el-input v-model="salonObj.terms" />
        </el-form-item>
        <!-- <el-form-item v-show="title == '编辑'" label="履约周期">
          <el-input v-model="salonObj.period" />
        </el-form-item> -->
        <el-form-item v-show="title == '新增'" label="履约周期">
          <el-date-picker v-model="beginTime" style="width: 200px;margin-right: 15px;" type="date" placeholder="起始日期" />-
          <el-date-picker v-model="endTime" style="width: 200px;margin-left: 10px;" type="date" placeholder="结束日期" />
        </el-form-item>
        <el-form-item label="问题">
          <el-input
            v-model="salonObj.problem"
            :autosize="{ minRows: 2, maxRows: 4 }"
            type="textarea"
          />
        </el-form-item>
        <el-form-item label="解决方案">
          <el-input
            v-model="salonObj.solution"
            :autosize="{ minRows: 2, maxRows: 4 }"
            type="textarea"
          />
        </el-form-item>
      </el-form>

      <!-- <div slot="footer" class="dialog-footer" style="margin-top: -30px;">
        <el-button @click="dialogFormVisible = false"> 取消 </el-button>
        <el-button type="primary" @click="updateData()"> 确定 </el-button>
      </div> -->
    </el-dialog>

    <el-dialog
      :title="salonObj.sname"
      :visible.sync="dialogFormVisible2"
      style="margin-top: -100px;"
    >
      <el-form
        label-width="0px"
        style="margin-left: 0px"
      >
        <el-form-item style="margin-bottom: 0px">
          <div>跟进信息</div>
          <el-row :gutter="20">
            <el-col :span="18" :offset="0">
              <el-input v-model="track" />
            </el-col>
            <el-col :span="6" :offset="0">
              <el-button type="primary" @click="handleTags">添加</el-button>
            </el-col>
          </el-row>
          <p v-html="salonObj.track" />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="dialogFormVisible2 = false"> 离开 </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getSalonList2, addSalon, editSalon, delSalon, updateTrack, getBigbs, getSomeSalon, changeStoreFrozen, countConsumerBySalons } from '@/api/txs'
import { getAdminsByDuties, countBySalons } from '@/api/admin'
import { regionData, codeToText } from 'element-china-area-data'
import pinyin from 'js-pinyin'
import dayjs from 'dayjs'
import Pagination from '@/components/Pagination'
import { mapGetters } from 'vuex'

export default {
  components: { Pagination },
  filters: {
    parseTime (time) {
      if(time) {
        return dayjs(time).format('YYYY-MM-DD')
      }
    },
    parseStatus (status) {
      switch(status) {
        case 0:
          return '履约期'
        case 1:
          return '试用期'
        case 2:
          return '停滞期'
      }
    }
  },
  data () {
    return {
      lstCountAccount: [],
      lstCountConsumer: [],
      cdtSname: '',
      cdtAddress: '',
      cdtMname: '',
      cdtDeveloper: '',
      cdnStatus: undefined,
      listB: [],
      beginTime: '',
      endTime: '',
      total: 0,
      listQuery: {
        page: 1,
        limit: 12
      },
      lstComms: [],
      lstYm: [],
      checkList: [],
      location: '四川省成都市武侯区',
      selectedOptions: ['51', '5101', '510107'],
      addr2: '',
      areaSelectData: regionData,
      dialogFormVisible: false,
      dialogFormVisible2: false,
      track: '',
      salonCode: 'SCCD' + dayjs().format('YYMMDD').slice(1),
      salonObj: {
        id: undefined,
        bid: 0,
        code: '',
        sname: '',
        address: '',
        area: 0,
        pic: '',
        stype: '',
        chat: '',
        developer: '',
        tel: '',
        cnumber: 0,
        bigbend: '',
        track: '',
        createTime: new Date(),
        status: 0,
        server: '',
        history: '',
        mid: undefined,
        oid: undefined,
        mname: ''
      },
      title: '',
      list: null,
      listLoading: true,
      rules: {
        sname: [{ required: true, message: '必填项', trigger: 'blur' }]
      }
    }
  },
  // watch: {
  //   dialogFormVisible: {
  //     handler () {
  //       this.selectedOptions = ['51', '5101', '510107']
  //     },
  //     immediate: true,
  //     deep: true
  //   }
  // },
  computed: {
    ...mapGetters([
      'name', 'id'
    ])
  },
  created () {
    getAdminsByDuties(21, 1, 999, 5, 0).then(
      res => {
        this.lstComms = res.data.data.records
      }
    )
    getAdminsByDuties(14, 1, 999, 5, 0).then(
      res => {
        this.lstYm = res.data.data.records
      }
    )
    this.fetchData()
  },
  methods: {
    nav2Account(row) {
      // this.$router.push({ path: '/user/:id', params: { id: 123 } })
      this.$router.push({ path: 'user/' + row.id });
    },
    nav2Consumer(row) {
      this.$router.push({ path: 'client/' + row.id + "/all" });
    },
    frozeStore(row, froze) {
      row.isFrozen = froze
      const dataInfo = new FormData()
      dataInfo.append('froze', froze)
      changeStoreFrozen(row.id, dataInfo)
    },
    searchSalon() {
      if(this.cdnStatus !== undefined || this.cdtAddress !== '' || this.cdtDeveloper !== '' || this.cdtMname !== '' || this.cdtSname !== '') {
        this.listLoading = true
        getSomeSalon(this.cdnStatus, this.cdtSname, this.cdtAddress, this.cdtMname, this.cdtDeveloper, this.id).then(res => {
          this.list = res.data.data
          // this.list.forEach(element => {
          //   if (element.status === 1){
          //     element.period = ''
          //   }
          // })
          this.total = 0
          this.listLoading = false
        })
      }
    },
    resetSalon () {
      this.cdnStatus = undefined
      this.cdtSname = ''
      this.cdtAddress = ''
      this.cdtMname = ''
      this.cdtDeveloper = ''
      this.listLoading = true
      getSalonList2(1, 12, '', '', undefined, this.id).then(res => {
        this.list = res.data.data.records
        // this.list.forEach(element => {
        //   if (element.status === 1){
        //     element.period = ''
        //   }
        // })
        this.total = res.data.data.total
        this.listLoading = false
      })
    },
    locationHandleChange () {
      this.location =
        codeToText[this.selectedOptions[0]] +
        codeToText[this.selectedOptions[1]] +
        codeToText[this.selectedOptions[2]]
      this.salonCode =
        pinyin.getCamelChars(codeToText[this.selectedOptions[0]]).slice(0, 2) +
        pinyin.getCamelChars(codeToText[this.selectedOptions[1]]).slice(0, 2) +
        dayjs().format('YYMMDD').slice(1)
    },
    async fetchData () {
      this.listLoading = true
      getBigbs().then(res => {
        this.listB = res.data.data
      })
      const resSn = await getSalonList2(this.listQuery.page, this.listQuery.limit, '', '', undefined, this.id)
      this.list = resSn.data.data.records
      this.total = resSn.data.data.total

      if(this.list && this.list.length > 0) {
        const params = this.list.map(item => item.id)
        const [resAt, resCr] = await Promise.all([
          countBySalons(params),
          countConsumerBySalons(params),
        ])

        this.lstCountAccount = resAt.data.data
        this.lstCountConsumer = resCr.data.data
        // console.log(this.lstCountAccount);
        // console.log(this.lstCountConsumer);

        this.list.forEach(s => {
          const at = this.lstCountAccount.find(a => a.sid === s.id+'')
          const cr = this.lstCountConsumer.find(c => c.sid === s.id)
          this.$set(s, 'accountNum', at ? at.ct : 0)
          this.$set(s, 'consumerNum', cr ? cr.ct : 0)
        });
      }
      this.listLoading = false

      // getSalonList2(this.listQuery.page, this.listQuery.limit, '', '', undefined, this.id).then(res => {
      //   this.list = res.data.data.records
      //   // this.list.forEach(element => {
      //   //   if (element.status === 1){
      //   //     element.period = ''
      //   //   }
      //   // })
      //   if(this.list && this.list.length > 0) {
      //     // const params = new URLSearchParams()
      //     // this.list.map(item => params.append('ids', item+''))
      //     const params = this.list.map(item => item.id)
      //     // countBySalons(params).then(res=>{
      //     //   this.lstCountAccount = res.data.data
      //     // })
      //     // countConsumerBySalons(params).then(res=>{
      //     //   this.lstCountConsumer = res.data.data
      //     // })
      //   }

      //   this.total = res.data.data.total
      //   this.listLoading = false
      // })

    },
    handleCreate () {
      this.title = '新增'
      this.salonObj = this.$options.data().salonObj
      this.checkList = []
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleUpdate (row) {
      this.title = '查看'
      this.dialogFormVisible = true
      this.salonObj = Object.assign({}, row)
      if (this.salonObj.stype) {
        this.checkList = this.salonObj.stype.split(' ')
      } else {
        this.checkList = []
      }
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData () {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          const tempData = Object.assign({}, this.salonObj)
          if (tempData.mid && tempData.mid !== 0) {
            tempData.mname = this.lstComms.find(c => {
              return c.id === tempData.mid
            }).nickName
          }
          if (this.title === '新增') {
            tempData.createTime = undefined
            tempData.address = this.location + '-' + this.addr2
            tempData.code = this.salonCode
            tempData.stype = this.checkList.join(' ')
            let bgTime = '【 2023年07月27日 】 '
            let edTime = '至 【 2033年07月27日 】'
            if (this.beginTime !== '') {
              bgTime = '【 ' + dayjs(this.beginTime).format('YYYY年MM月DD日') + ' 】 '
              tempData.bgntime = this.beginTime
            }
            if (this.endTime !== '') {
              edTime = '至 【 ' + dayjs(this.endTime).format('YYYY年MM月DD日') + ' 】'
              tempData.endtime = this.endTime
            }
            tempData.period = bgTime + edTime
            tempData.deadline = dayjs().add(30, 'day')
            tempData.quota = 10
            addSalon(tempData).then(res => {
              const d = res.data.data
              this.list.unshift(d)
              this.dialogFormVisible = false
              this.$notify({
                title: res.data.message,
                message: res.data.status,
                type: 'success',
                duration: 2000
              })
            })
          } else if (this.title === '查看') {
            tempData.stype = this.checkList.join(' ')
            editSalon(tempData).then(() => {
              const index = this.list.findIndex(v => v.id === this.salonObj.id)
              this.list.splice(index, 1, tempData)
              this.dialogFormVisible = false
              this.$notify({
                title: 'Success',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
            })
          }
        }
      })
    },
    salonInfo (row) {
      this.dialogFormVisible2 = true
      this.salonObj = Object.assign({}, row)
    },
    handleDelete (id, index) {
      this.$confirm('确定要删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          delSalon(id).then(() => {
            this.$notify({
              title: 'Success',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
          })
          this.list.splice(index, 1)
        })
        .catch(() => {})
    },
    handleTags() {
      let track = ''
      track = dayjs(new Date()).format('YY-MM-DD') + ' ' + this.name + '：' + this.track
      if (this.salonObj.track && this.salonObj.track.length > 0) {
        this.salonObj.track = track + '<br>' + this.salonObj.track
      } else {
        this.salonObj.track = track
      }

      updateTrack(this.salonObj.id, track).then(() => {
        this.$notify({
          title: 'Success',
          message: '添加成功',
          type: 'success',
          duration: 2000
        })
      })
      const index = this.list.findIndex(v => v.id === this.salonObj.id)
      this.list.splice(index, 1, this.salonObj)
    }
  }
}
</script>
